 // pages/upJob/upJob.js
 const db = wx.cloud.database({
     env: 'work1-0g1b3grp436e9236'
 })
 const dayjs = require('../../miniprogram_npm/miniprogram_npm/dayjs/index')
 const util = require("../../utils/util")

 Page({

     /**
      * 页面的初始数据
      */
     data: {
         jobName: '',
         salary: '',
         needNum: '',
         jobAddress: '',
         location: '',
         locationGeo: '',
         // 选择日历
         minDate: new Date(2022, 6, 1).getTime(),
         maxDate: new Date(2022, 12, 31).getTime(),
         showCalendar: false,
         period: '',
         content: '',
         // 用户已经选择的tags
         tags: [],
         newTag: '',
         // 供用户选择的tags
         userTags: ['包餐', '包住宿', '薪资高', '劳动量不高', '餐费补贴', '房租补贴', '村民和善', '卫生条件好', '交通便利', '低技术含量', '高技术含量'],
         // 判断是否从map页返回
         isCloseToMap: false,
         advantage: '',
         showAdvantageAction: false,
         category: '',
         categoryActions: [],
         showCategoryAction: false,
         newCategory: '',
         // 右
         mainActiveIndex: 0,
         activeId: 0,
         // 职业分类列表
         jobCategoryItems: [{
                 text: '农业相关',
                 badge: 10,
                 children: [{
                         text: '育种',
                         id: 1,
                     },
                     {
                         text: '作物保护与检疫',
                         id: 2,
                     },
                     {
                         text: '粮食类生产与加工',
                         id: 3,
                     },
                     {
                         text: '蔬菜类生产与加工',
                         id: 4,
                     },
                     {
                         text: '水果类生产与加工',
                         id: 5,
                     },
                     {
                         text: '中草药栽培与加工',
                         id: 6,
                     },
                     {
                         text: '茶叶生产与加工',
                         id: 7,
                     },
                     {
                         text: '烟草栽培与加工',
                         id: 8,
                     },
                     {
                         text: '食用菌生产与加工',
                         id: 9,
                     },
                     {
                         text: '棉花栽培与加工',
                         id: 10,
                     },
                 ],
             },
             {
                 text: '林业相关',
                 badge: 5,
                 children: [{
                         text: '种子生产',
                         id: 1,
                     },
                     {
                         text: '林木育苗',
                         id: 2,
                     },
                     {
                         text: '病虫害防治',
                         id: 3,
                     },
                     {
                         text: '森林营造',
                         id: 4,
                     },
                     {
                         text: '经济林产品生产与加工',
                         id: 5,
                     },
                 ],
             },
             {
                 text: '畜牧业相关',
                 badge: 8,
                 children: [{
                         text: '育仔',
                         id: 1,
                     },
                     {
                         text: '动物防疫与检疫',
                         id: 2,
                     },
                     {
                         text: '动物饲养',
                         id: 3,
                     },
                     {
                         text: '蚕桑相关',
                         id: 4,
                     },
                     {
                         text: '肉类产品加工',
                         id: 5,
                     },
                     {
                         text: '蛋类产品加工',
                         id: 6,
                     },
                     {
                         text: '奶类产品加工',
                         id: 7,
                     },
                     {
                         text: '皮毛类产品加工',
                         id: 8,
                     },
                 ],
             },
             {
                 text: '渔业相关',
                 badge: 5,
                 children: [{
                         text: '育苗',
                         id: 1,
                     },
                     {
                         text: '保护与检疫',
                         id: 2,
                     },
                     {
                         text: '淡水渔类饲养',
                         id: 3,
                     },
                     {
                         text: '海洋鱼类加工',
                         id: 4,
                     },
                     {
                         text: '捕捞与加工',
                         id: 5,
                     },
                 ],
             },
             {
                 text: '机械与自动化相关',
                 badge: 4,
                 children: [{
                         text: '农业智能化装备应用',
                         id: 1,
                     },
                     {
                         text: '畜禽智能化装备应用',
                         id: 2,
                     },
                     {
                         text: '木业智能化装备应用',
                         id: 3,
                     },
                     {
                         text: '现代化系统设计（大型工程需谨慎）',
                         id: 4,
                     },
                 ],
             },
             {
                 text: '电商与运输',
                 badge: 4,
                 children: [{
                         text: '农副产品销售',
                         id: 1,
                     },
                     {
                         text: '休闲旅游推广',
                         id: 2,
                     },
                     {
                         text: '特色产业、产品宣传',
                         id: 3,
                     },
                     {
                         text: '客运',
                         id: 4,
                     },
                     {
                         text: '货运',
                         id: 5,
                     },
                     {
                         text: '招商引资代理',
                         id: 6,
                     },

                 ],
             },
             {
                 text: '服务业相关',
                 badge: 5,
                 children: [{
                         text: '酒店服务员',
                         id: 1,
                     },
                     {
                         text: '厨师',
                         id: 2,
                     },
                     {
                         text: '保洁',
                         id: 3,
                     },
                     {
                         text: '保安',
                         id: 4,
                     },
                     {
                         text: '导游',
                         id: 5,
                     },
                 ],
             },
         ],
         // 更新过定位
         hasUpdatedJobAddress: false
     },

     submit() {
         if (this.checkJobName() && this.checkSalary() && this.checkNeedNum() && this.checkAdvantage() &&
             this.checkJobAddress() && this.checkPeriod() && this.checkContent()) {
             wx.showLoading({
                 title: '正在保存...'
             })
             const currentLocation = wx.getStorageSync('currentLocation')
             const params = {
                 beginTime: this.data.beginTime,
                 endTime: this.data.endTime,
                 content: this.data.content,
                 continueTime: this.data.continueTime,
                 jobAddress: this.data.jobAddress,
                 jobName: this.data.jobName,
                 location: currentLocation.location.split(',')[3],
                 locationGeo: {
                     "type": "Point",
                     "coordinates": currentLocation.geo
                 },
                 needNum: parseInt(this.data.needNum, 10),
                 remainNum: parseInt(this.data.needNum, 10),
                 postNum: 0,
                 status: 1,
                 salary: parseInt(this.data.salary, 10),
                 tags: this.data.tags,
                 category: this.data.category,
                 updateTime: new Date(),
                 userId: wx.getStorageSync('userInfo').userId
             }
             if (this.data.toUpdate) {
                 if (!this.data.hasUpdatedJobAddress) {
                     params.location = this.data.location
                     params.locationGeo = this.data.locationGeo
                 }
                 console.log(params)
                 db.collection('work_job').doc(this.data.toUpdateJobid).update({
                     data: params
                 }).then(res => {
                     wx.hideLoading({})
                     wx.redirectTo({
                         url: '/pages/firm/firm?toUpdate=1&id=' + this.data.companyId,
                     })
                 })
                 return
             }
             //新增job
             db.collection('work_job').add({
                 data: params
             }).then(res => {
                 // console.log(res)
                 const id = res._id
                 wx.hideLoading({
                     success: (res) => {
                         wx.redirectTo({
                             url: '/pages/job-detail/job-detail?id=' + id,
                         })
                     },
                 })
             })
         }
     },

     // 获取定位
     toMap() {
         this.setData({
             isCloseToMap: true
         })
         wx.navigateTo({
             url: '/pages/map/map',
         })
     },

     // tags
     onCloseAdvantageAction() {
         this.checkAdvantage()
         this.setData({
             showAdvantageAction: false
         })
     },

     onOpenAdvantageAction() {
         this.checkAdvantage()
         this.setData({
             showAdvantageAction: true
         })
     },

     // 选择职业分类
     onOpenCategoryAction() {
         this.setData({
             showCategoryAction: true
         })
     },

     addNewCategory() {
         if (!this.data.newCategory) {
             util.myToastNone('输入为空')
             return
         }
         this.setData({
             category: this.data.newCategory,
             showCategoryAction: false
         })
     },

     onCloseCategoryAction() {
         this.setData({
             showCategoryAction: false
         })
         this.checkCategory()
     },

     // 点击职业类型
     onClickNav({
         detail = {}
     }) {
         this.setData({
             mainActiveIndex: detail.index || 0,
         });
     },

     // 选择具体职业
     onClickItem({
         detail = {}
     }) {
         const activeId = this.data.activeId === detail.id ? null : detail.id;
         this.setData({
             activeId
         })
         this.setData({
             category: detail.text,
             showCategoryAction: false
         })
         this.checkCategory()
     },

     // 用户手动添加
     addNewTag() {
         if (this.data.newTag) {
             this.data.tags.push(this.data.newTag)
             const tags = [...new Set(this.data.tags)]
             this.setData({
                 tags: tags
             })
             this.setData({
                 advantage: this.data.tags.join(', '),
                 newTag: ''
             })
            //  console.log(this.data.tags)
         }
     },

     // 从已有的tags中选择
     addTag(e) {
         const newTag = e.currentTarget.dataset.tag
         this.data.tags.push(newTag)
         const tags = [...new Set(this.data.tags)]
         this.setData({
             tags: tags
         })
         this.setData({
             advantage: this.data.tags.join(', ')
         })
     },

     // 手动修改tags
     makeTagsAgain({detail}) {
        this.setData({
            tags: detail.split(', ')
        })
     },

     // 日历相关
     onDisplayCalendar() {
         this.setData({
             showCalendar: true
         })
     },
     onCloseCalendar() {
         this.checkPeriod()
         this.setData({
             showCalendar: false
         })
         // this.selectComponent('#calendar').toggle(false);
     },
     formatDate(date) {
         date = new Date(date);
         return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
     },
     onConfirmCalendar(event) {
         const [start, end] = event.detail
         // const continueTime = end.getDate() - start.getDate() + 1
         const continueTime = this.getDays(start, end)
         this.setData({
             showCalendar: false,
             period: `${this.formatDate(start)}至${this.formatDate(end)}(${continueTime}天)`,
             beginTime: start,
             endTime: end,
             continueTime
         })
         // console.log(this.data.continueTime)
         this.checkPeriod()
         // this.selectComponent('#calendar').toggle(false);
     },
     // 计算时间差
     getDays(start, end) {
         let dateSpan, iDays
         start = Date.parse(start)
         end = Date.parse(end)
         dateSpan = end - start
         dateSpan = Math.abs(dateSpan)
         iDays = Math.floor(dateSpan / (24 * 3600 * 1000))
         return iDays + 1
     },

     checkCategory() {
         if (!this.data.category) {
             this.setData({
                 categoryErr: '请选择职位分类'
             })
             return false
         }
         this.setData({
             categoryErr: ''
         })
         return true
     },

     checkAdvantage() {
         if (!this.data.advantage) {
             this.setData({
                 advantageErr: '请选择职位优势'
             })
             return false
         }
         this.setData({
             advantageErr: ''
         })
         return true
     },

     checkContent() {
         if (!this.data.content) {
             this.setData({
                 contentErr: '请输入工作内容'
             })
             return false
         }
         this.setData({
             contentErr: ''
         })
         return true
     },

     checkPeriod() {
         if (!this.data.period) {
             this.setData({
                 periodErr: '请选择起止时间'
             })
             return false
         }
         this.setData({
             periodErr: ''
         })
         return true
     },

     checkJobAddress() {
         if (!this.data.jobAddress) {
             this.setData({
                 jobAddressErr: '请输入公司地址'
             })
             return false
         }
         this.setData({
             jobAddressErr: ''
         })
         return true
     },

     checkNeedNum() {
         if (!this.data.needNum) {
             this.setData({
                 needNumErr: '请输入职位数量'
             })
             return false
         }
         this.setData({
             needNumErr: ''
         })
         return true
     },

     checkSalary() {
         if (!this.data.salary) {
             this.setData({
                 salaryErr: '请填写薪资情况'
             })
             return false
         }
         this.setData({
             salaryErr: ''
         })
         return true
     },

     checkJobName() {
         if (!this.data.jobName) {
             this.setData({
                 jobNameErr: '请输入职位名称'
             })
             return false
         }
         this.setData({
             jobNameErr: ''
         })
         return true
     },

     /**
      * 生命周期函数--监听页面加载
      */
     onLoad(options) {
         this.setData({
             companyId: options.companyId
         })
         let jobid = options.id
         if (jobid) {
             this.setData({
                 toUpdate: true,
                 toUpdateJobid: jobid
             })
             db.collection('work_job').doc(jobid).get().then(res => {
                 this.setData({
                     jobName: res.data.jobName,
                     salary: res.data.salary,
                     needNum: res.data.needNum,
                     tags: res.data.tags,
                     advantage: res.data.tags.join(', '),
                     category: res.data.category,
                     jobAddress: res.data.jobAddress,
                     beginTime: res.data.beginTime,
                     endTime: res.data.endTime,
                     continueTime: res.data.continueTime,
                     content: res.data.content,
                     location: res.data.location,
                     locationGeo: res.data.locationGeo
                 })
                 this.setData({
                     period: `${this.formatDate(this.data.beginTime)}至${this.formatDate(this.data.endTime)}(${this.data.continueTime}天)`,
                 })
             })
         }
         const time = new Date()
         this.setData({
             minDate: new Date(time.getFullYear(), time.getMonth(), time.getDate()).getTime()
         })
     },

     /**
      * 生命周期函数--监听页面初次渲染完成
      */
     onReady() {

     },

     /**
      * 生命周期函数--监听页面显示
      */
     onShow() {
         // 获取地理位置
         // console.log(this.data.isCloseToMap)
         if (this.data.isCloseToMap) {
             const currentLocation = wx.getStorageSync('currentLocation')
             this.setData({
                 jobAddress: currentLocation.address,
                 hasUpdatedJobAddress: true
             })
             // console.log(this.data.jobAddress)
             this.checkJobAddress()
         }
         this.setData({
             isCloseToMap: false
         })
     },

     /**
      * 生命周期函数--监听页面隐藏
      */
     onHide() {

     },

     /**
      * 生命周期函数--监听页面卸载
      */
     onUnload() {

     },

     /**
      * 页面相关事件处理函数--监听用户下拉动作
      */
     onPullDownRefresh() {

     },

     /**
      * 页面上拉触底事件的处理函数
      */
     onReachBottom() {

     },

     /**
      * 用户点击右上角分享
      */
     onShareAppMessage() {

     }
 })